import { Router } from 'express';
import { body } from 'express-validator';
import validateFormData from '../helpers/validate_form.js';
import DB from '../models/db.js';
import crypto from 'crypto';

const router = Router();

/**
 * Route to list API keys
 * @GET /apikeys/index/{fieldname}/{fieldvalue}
 */
router.get(['/', '/index/:fieldname?/:fieldvalue?'], async (req, res) => {  
    try {
        const query = {};
        let queryFilters = [];
        let where = {};
        let replacements = {};
        let fieldName = req.params.fieldname;
        let fieldValue = req.params.fieldvalue;
        
        if (fieldName) {
            queryFilters.push(DB.filterBy(fieldName, fieldValue));
        }
        let search = req.query.search;
        if(search) {
            let searchFields = DB.ApiKeys.searchFields();
            where[DB.op.or] = searchFields;
            replacements.search = `%${search}%`;
        }

        // 根据用户角色过滤数据
        let allowedRoles = ["admin", "eduadmin"];
        let userRole = req.userRoleName;
        if(!allowedRoles.includes(userRole)) {
            // 获取用户关联的企业申请ID
            const employerApplication = await DB.EmployerApplications.findOne({
                where: { contact_email: req.user.email }
            });
            if (employerApplication) {
                where['employer_id'] = employerApplication.application_id;
            } else {
                return res.forbidden('您没有权限访问API密钥');
            }
        }

        if(queryFilters.length) {
            where[DB.op.and] = queryFilters;
        }

        query.raw = true;
        query.where = where;
        query.replacements = replacements;
        query.order = DB.getOrderBy(req, 'key_id', 'desc');
        query.attributes = DB.ApiKeys.listFields();
        
        // 添加与企业申请的关联查询
        query.include = [{
            model: DB.EmployerApplications,
            as: 'employer',
            attributes: ['company_name'],
            required: false
        }];

        let page = parseInt(req.query.page) || 1;
        let limit = parseInt(req.query.limit) || 10;
        let result = await DB.ApiKeys.paginate(query, page, limit);

        // 处理结果，将公司名称添加到每条记录中
        if (result.records) {
            result.records = result.records.map(record => ({
                ...record,
                company_name: record['employer.company_name'] || '未知公司'
            }));
        }

        return res.ok(result);
    }
    catch(err) {
        return res.serverError(err);
    }
});

/**
 * Route to view API key record
 * @GET /apikeys/view/{recid}
 */
router.get('/view/:recid', async (req, res) => {
    try {
        const recid = req.params.recid || null;
        const query = {}
        const where = {}
        where['key_id'] = recid;
        query.raw = true;
        query.where = where;
        query.attributes = DB.ApiKeys.viewFields();
        let record = await DB.ApiKeys.findOne(query);
        if(!record) {
            return res.notFound();
        }
        return res.ok(record);
    }
    catch(err) {
        return res.serverError(err);
    }
});

/**
 * Route to create new API key
 * @POST /apikeys/add
 */
router.post('/add/', 
    [
        body('employer_id').not().isEmpty().isNumeric().withMessage('企业ID不能为空'),
        body('name').not().isEmpty().withMessage('密钥名称不能为空'),
        body('description').optional(),
        body('permissions').optional(),
        body('expires_at').optional().isISO8601().withMessage('过期时间格式不正确'),
    ], validateFormData
, async function (req, res) {
    try {
        let modeldata = req.getValidFormData();
        
        // 检查企业申请是否存在且已通过审核
        const employerApplication = await DB.EmployerApplications.findOne({
            where: { 
                application_id: modeldata.employer_id,
                application_status: 'approved'
            }
        });

        if (!employerApplication) {
            return res.badRequest('企业申请不存在或未通过审核');
        }

        // 生成API密钥和密钥
        const apiKey = crypto.randomBytes(32).toString('hex');
        const apiSecret = crypto.randomBytes(64).toString('hex');

        // 设置初始状态为激活
        modeldata.status = 'active';
        modeldata.api_key = apiKey;
        modeldata.api_secret = apiSecret;
        
        // 保存记录
        let record = await DB.ApiKeys.create(modeldata);
        
        // 返回成功信息，包含API密钥信息
        return res.ok({
            success: true,
            message: 'API密钥创建成功',
            key_id: record.key_id,
            name: record.name,
            api_key: record.api_key,
            api_secret: record.api_secret,
            status: record.status,
            expires_at: record.expires_at,
            created_at: record.created_at
        });
    } catch(err) {
        console.error('创建API密钥时出错:', err);
        return res.serverError('创建API密钥失败，请稍后重试');
    }
});

/**
 * Route to update API key
 * @POST /apikeys/edit/{recid}
 */
router.post('/edit/:recid', 
    [
        body('name').optional(),
        body('description').optional(),
        body('permissions').optional(),
        body('status').optional().isIn(['active', 'inactive', 'revoked'])
            .withMessage('状态只能是 active、inactive 或 revoked'),
        body('expires_at').optional().isISO8601().withMessage('过期时间格式不正确'),
    ], validateFormData
, async (req, res) => {
    try {
        const recid = req.params.recid;
        let modeldata = req.getValidFormData({ includeOptionals: true });
        
        const query = {};
        const where = {};
        where['key_id'] = recid;
        query.raw = true;
        query.where = where;
        
        let record = await DB.ApiKeys.findOne(query);
        if(!record) {
            return res.notFound();
        }

        // 更新记录
        await DB.ApiKeys.update(modeldata, {where: where});
        
        // 获取更新后的记录
        record = await DB.ApiKeys.findOne({
            where: where,
            include: [{
                model: DB.EmployerApplications,
                as: 'employer',
                attributes: ['company_name'],
                required: false
            }],
            raw: true
        });

        // 返回更新后的记录
        return res.ok({
            ...record,
            company_name: record['employer.company_name'] || '未知公司'
        });
    }
    catch(err) {
        console.error('更新API密钥时出错:', err);
        return res.serverError(err);
    }
});

/**
 * Route to delete API key
 * @GET /apikeys/delete/{recid}
 */
router.get('/delete/:recid', async (req, res) => {
    try {
        const recid = (req.params.recid || '').split(',');
        const query = {};
        const where = {};
        where['key_id'] = recid;
        query.raw = true;
        query.where = where;
        
        await DB.ApiKeys.destroy(query);
        return res.ok(recid);
    }
    catch(err) {
        return res.serverError(err);
    }
});

export default router; 